<template>
  <main class="flex-1 p-8 bg-gray-100">
    <div class="bg-white rounded-lg shadow-md p-6">
      <!-- 搜索和操作区 -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex space-x-4">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入权限名称"
            class="w-64"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="statusFilter" placeholder="权限状态" class="w-32">
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </div>
        <div class="space-x-2">
          <el-button type="primary" icon="Plus" class="!rounded-button whitespace-nowrap" @click="showAddDialog">新增权限</el-button>
          <el-button type="danger" icon="Delete" class="!rounded-button whitespace-nowrap" @click="showBatchDeleteDialog">批量删除</el-button>
        </div>
      </div>

      <!-- 权限树形表格 -->
      <el-table
        :data="filteredPermissions"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限标识" />
        <el-table-column prop="description" label="权限描述" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" icon="Edit" size="small" class="!rounded-button whitespace-nowrap" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" icon="Delete" size="small" class="!rounded-button whitespace-nowrap" @click="showSingleDeleteDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog title="编辑权限" v-model="isEditDialogVisible">
        <el-form :model="editForm">
          <el-form-item label="权限名称" label-width="100px">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="权限标识" label-width="100px">
            <el-input v-model="editForm.code"></el-input>
          </el-form-item>
          <el-form-item label="权限描述" label-width="100px">
            <el-input v-model="editForm.description" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isEditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdatePermission">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新增弹窗 -->
      <el-dialog title="新增权限" v-model="isAddDialogVisible">
        <el-form :model="addForm">
          <el-form-item label="权限名称" label-width="100px">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="权限标识" label-width="100px">
            <el-input v-model="addForm.code"></el-input>
          </el-form-item>
          <el-form-item label="权限描述" label-width="100px">
            <el-input v-model="addForm.description" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isAddDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleCreatePermission">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 单行删除弹窗 -->
      <el-dialog title="确认删除" v-model="isSingleDeleteDialogVisible">
        <p>确定要删除权限 <strong>{{ singleRowToDelete?.name }}</strong> 吗？</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isSingleDeleteDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSingleDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量删除弹窗 -->
      <el-dialog title="确认批量删除" v-model="isBatchDeleteDialogVisible">
        <p>确定要删除所选权限吗？</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isBatchDeleteDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleBatchDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </main>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Delete, Edit } from '@element-plus/icons-vue';

const searchKeyword = ref('');
const statusFilter = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(100);

const permissionData = ref([
  {
    id: 1,
    name: '系统管理',
    code: 'system',
    description: '系统管理相关权限',
    status: true,
    children: [
      { id: 11, name: '用户管理', code: 'system:user', description: '用户管理相关权限', status: true },
      { id: 12, name: '角色管理', code: 'system:role', description: '角色管理相关权限', status: true },
      { id: 13, name: '菜单管理', code: 'system:menu', description: '菜单管理相关权限', status: false },
    ],
  },
  {
    id: 2,
    name: '内容管理',
    code: 'content',
    description: '内容管理相关权限',
    status: true,
    children: [
      { id: 21, name: '文章管理', code: 'content:article', description: '文章管理相关权限', status: true },
      { id: 22, name: '评论管理', code: 'content:comment', description: '评论管理相关权限', status: false },
    ],
  },
  {
    id: 3,
    name: '数据统计',
    code: 'statistics',
    description: '数据统计相关权限',
    status: true,
  },
]);

const filteredPermissions = computed(() => {
  let filtered = permissionData.value.filter(permission =>
    permission.name.includes(searchKeyword.value) &&
    (statusFilter.value === '' || permission.status.toString() === statusFilter.value)
  );
  return filtered.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});

const handleStatusChange = (row) => {
  ElMessage.success(`${row.name}权限状态已${row.status ? '启用' : '禁用'}`);
};

const handleEdit = (row) => {
  editForm.value = { ...row };
  isEditDialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessage.warning(`删除权限：${row.name}`);
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  // 这里应该重新加载数据
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 这里应该重新加载数据
};

const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);
const isSingleDeleteDialogVisible = ref(false);
const isBatchDeleteDialogVisible = ref(false);

const selectedRows = ref([]);

const editForm = ref({});
const addForm = ref({});
const singleRowToDelete = ref(null);

const showAddDialog = () => {
  isAddDialogVisible.value = true;
};

const handleUpdatePermission = () => {
  // 更新权限的逻辑
  isEditDialogVisible.value = false;
  ElMessage.success('权限已更新');
};

const handleCreatePermission = () => {
  // 添加新权限的逻辑
  isAddDialogVisible.value = false;
  ElMessage.success('权限已添加');
};

const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const showSingleDeleteDialog = (row) => {
  singleRowToDelete.value = row;
  isSingleDeleteDialogVisible.value = true;
};

const handleSingleDelete = () => {
  const index = permissionData.value.findIndex(item => item.id === singleRowToDelete.value.id);
  if (index !== -1) {
    permissionData.value.splice(index, 1);
    isSingleDeleteDialogVisible.value = false;
    ElMessage.success('权限已删除');
  }
};

const showBatchDeleteDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要删除的权限');
    return;
  }
  isBatchDeleteDialogVisible.value = true;
};

const handleBatchDelete = () => {
  const idsToDelete = selectedRows.value.map(row => row.id);
  permissionData.value = permissionData.value.filter(item => !idsToDelete.includes(item.id));
  isBatchDeleteDialogVisible.value = false;
  ElMessage.success('权限已批量删除');
};

onMounted(() => {
  // 这里可以加载初始数据
});
</script>

<style scoped>
/* 自定义样式 */
.el-table {
  --el-table-border-color: #e5e7eb;
  --el-table-header-background-color: #f3f4f6;
}

.el-pagination {
  --el-pagination-button-color: #1f2937;
  --el-pagination-hover-color: #3b82f6;
}

/* 确保按钮文字不换行 */
.el-button {
  white-space: nowrap;
}

/* 移除 input type="number" 的默认箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}
</style>
